<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="javax.servlet.http.Cookie" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%
    // 增加总访问量统计
    Integer totalVisits = (Integer)application.getAttribute("totalVisits");
    if(totalVisits == null) {
        totalVisits = 0;
    }
    application.setAttribute("totalVisits", totalVisits + 1);

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String remember = request.getParameter("remember");

    // 获取模拟数据库
    Map<String, String> userDatabase = (Map<String, String>)application.getAttribute("userDatabase");
    if(userDatabase == null) {
        userDatabase = new HashMap<>();
        application.setAttribute("userDatabase", userDatabase);
    }

    // 验证用户
    if(userDatabase.containsKey(username) && userDatabase.get(username).equals(password)) {
        // 验证成功，将用户名存入session
        session.setAttribute("username", username);

        // 增加当前在线用户数
        Integer currentUsers = (Integer)application.getAttribute("currentUsers");
        if(currentUsers == null) {
            currentUsers = 0;
        }
        application.setAttribute("currentUsers", currentUsers + 1);

        // 记住我功能
        if("on".equals(remember)) {
            Cookie userCookie = new Cookie("rememberMeUser", username);
            userCookie.setMaxAge(30 * 24 * 60 * 60);
            response.addCookie(userCookie);

            Cookie rememberCookie = new Cookie("rememberMe", "true");
            rememberCookie.setMaxAge(30 * 24 * 60 * 60);
            response.addCookie(rememberCookie);
        }

        response.sendRedirect("index.jsp");
    } else {
        request.setAttribute("errorMsg", "用户名或密码错误！");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
%>